<template>
    <form @submit.prevent="btnSave">
      <table>
        <tbody>
          <tr>
            <td><label for="bookName">书名:</label></td>
            <td><input type="text" id="bookName" v-model="bookName"></td>
          </tr>
          <tr>
            <td><label for="author">作者:</label></td>
            <td><input type="text" id="author" v-model="author"></td>
          </tr>
          <tr>
            <td><input type="button" value="保存" @click="btnSave"></td>
            <td><input type="button" value="取消" @click="btnCancel"></td>
          </tr>
        </tbody>
      </table>
    </form>
  </template>
  
  <script setup>
  import { ref, onMounted,reactive } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { addItem, editItem, getById } from '@/api/bookApi';
  
  const router = useRouter();
  const route = useRoute();
  
  // 数据变量-开始 
  const bookName = ref('');
  const author = ref('');
  const bookId = ref(null);
  // 数据变量-结束 
  const id = route.params.id;
  
  // 动作函数-开始 
  function btnSave() {
    const bookData = reactive({

      id: bookId.value,
      bookName: bookName.value,
      author: author.value
    });
  
    if (bookId.value) {
      // 编辑现有图书
      editItem(id,bookData).then(() => {
        router.push('/book');
      }).catch(error => {
        console.error('编辑书籍失败:', error);
      });
    } else {
      // 添加新图书
      addItem(bookData).then(() => {
        router.push('/book');
      }).catch(error => {
        console.error('添加书籍失败:', error);
      });
    }
  }
  
  function btnCancel() {
    router.push('/book');
  }
  
  // 在组件挂载时检查是否为编辑模式
  onMounted(() => {
    
    console.log(id);
    
    if (id) {
      bookId.value = id;
      getById(id).then(res => {
        bookName.value = res.data.bookName;
        author.value = res.data.author;
      }).catch(error => {
        console.error('获取书籍详情失败:', error);
      });
    }
  });
  // 动作函数-结束 
  </script>
  